from PySide6.QtWidgets import QTabWidget
from .table_viewer import TableViewer

class TabArea(QTabWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.close_tab)
        self.opened_tables = {}

    def open_table(self, filename):
        # 如果已打开则切换，否则新建标签页
        if filename in self.opened_tables:
            idx = self.indexOf(self.opened_tables[filename])
            self.setCurrentIndex(idx)
        else:
            table_view = TableViewer(filename)
            idx = self.addTab(table_view, filename)
            self.setCurrentIndex(idx)
            self.opened_tables[filename] = table_view

    def close_tab(self, index):
        widget = self.widget(index)
        for fname, w in list(self.opened_tables.items()):#遍历字典
            if w == widget:
                del self.opened_tables[fname]
                break
        self.removeTab(index)
        widget.deleteLater()#删除widget
